<template>
  <div class="river-modal">
    <el-dialog width="40%" v-model="dialogVisible" :before-close="handleClose">
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header">
          <div>{{ state.title }}</div>
        </div>
      </template>
      <div class="river-box">
        <el-form
          ref="riverFormRef"
          :model="basinObj"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          status-icon
        >
          <el-form-item label="流域名称" prop="basinName">
            <el-input class="formwidth" placeholder="请输入" v-model="basinObj.basinName" />
          </el-form-item>
          <el-form-item label="流域说明" prop="basinDesc">
            <el-input
              class="formwidth"
              type="textarea"
              placeholder="请输入"
              v-model="basinObj.basinDesc"
            />
          </el-form-item>
          <div class="box-right">
            <el-form-item label="输入河系" prop="schemeType">
              <el-table
                ref="multipleTableRef"
                :data="state.riverList"
                class="areaTable"
                @select="handleSelectionRiver"
              >
                <el-table-column
                  property="rsysName"
                  label="河系名称"
                  show-overflow-tooltip
                  align="center"
                />
                <el-table-column type="selection" width="55" />
              </el-table>
            </el-form-item>
            <el-form-item label="输入区域" prop="schemeType">
              <el-table
                ref="multipleTableAreaRef"
                :data="state.tableData"
                class="areaTable"
                @select="handleSelectionCalc"
              >
                <el-table-column
                  property="calczName"
                  label="区域名称"
                  show-overflow-tooltip
                  align="center"
                />
                <el-table-column type="selection" width="55" />
              </el-table>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handleSave">保存</el-button>
          <el-button @click="handleClose()">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, defineExpose, nextTick } from 'vue'
import {
  getAreaList,
  getRsysList,
  // 根据河系查看区域接口
  getZonesListbyrs,
  // 回显流域查看河系
  getRsysListByZid,
  // 保存流域
  saveBasin,
  getBasinDetail
} from '@/services/modules/compute-methods'
const dialogVisible = ref(false)
const props = defineProps({
  watershedId: {
    type: Number,
    default: 1
  }
})
//验证
const rules = {
  basinName: [{ required: true, message: '请输入流域名称', trigger: 'blur' }]
}
const riverFormRef = ref(null)
const multipleTableRef = ref(null)
// 区域tableRef
const multipleTableAreaRef = ref(null)

const state = reactive({
  childIdArr: [],
  flag: false,

  title: '新建流域',
  graph: '',
  sec_topologData: {},
  tableData: [],
  riverList: [],
  selected: false
})
const areaList = ref([])
const areaCheckData = ref([])
// 河系已选中并转换的列表
const rsysData = ref([])
// 区域已选中并转换的列表
const areaData = ref([])
// 流域信息
const basinObj = ref({
  basinName: '',
  basinDesc: '',
  id: ''
})
// 获取全部区域
function getAllArea() {
  return new Promise((resolve, reject) => {
    getAreaList({ zoneId: props.watershedId }).then((res) => {
      if (res.code === 200) {
        areaList.value = res.data
        state.tableData = res.data
        resolve(res.data)
      }
    })
  })
}
// 获取河系
function rsysList() {
  return new Promise((resolve, reject) => {
    getRsysList({ zoneId: props.watershedId, rsysName: '' }).then((res) => {
      if (res.code === 200) {
        state.riverList = res.data
        resolve(res.data)
      }
    })
  })
}
// 根据河系获取区域列表

// 河系多选
function handleSelectionRiver(arr) {
  return new Promise((resolve, reject) => {
    // 将之前选中的河系清楚掉
    rsysData.value = []
    // 每次选择河系 则将右侧区域列表取消全部选中状态
    multipleTableAreaRef.value.clearSelection()
    state.tableData = []
    if (arr.length) {
      getZonesListbyrs({
        zoneId: props.watershedId,
        rsysIds: arr.map((item) => item.id).join(',')
      }).then((res) => {
        state.tableData = areaList.value.filter(
          (itemB) => !res.data.some((itemA) => itemA.id === itemB.id)
        )
        resolve(res)
        // 河系多选完之后判断是否是编辑
      })
    } else {
      state.tableData = areaList.value
    }
    // 将选中的河系暂存到河系已选中数组中
    arr.forEach((a) => {
      rsysData.value.push({
        childType: 1,
        childId: a.id
      })
    })
  })
}
// 区域多选
const handleSelectionCalc = (arr) => {
  areaData.value = []
  areaCheckData.value = arr
  arr.forEach((a) => {
    areaData.value.push({
      childType: 0,
      childId: a.id
    })
  })
}
const emit = defineEmits(['closeBasin'])
const closeBasin = () => {
  emit('closeBasin', false)
}
// 点击修改 回显流域信息
const handleBasinDetail = async (id) => {
  const hexiId = []
  const quyuId = []
  const res = await getBasinDetail({ basinId: id })
  if (res.code == 200) {
    basinObj.value = res.data
    res.data.children.forEach((item) => {
      // 河系
      if (item.childType === 1) {
        hexiId.push(item.childId)
      } else {
        quyuId.push(item.childId)
      }
    })

    const arr1 = state.riverList.filter((e) => {
      if (hexiId.includes(e.id)) {
        return e
      }
    })
    arr1.forEach((row) => {
      multipleTableRef.value.toggleRowSelection(row, true)
    })
    await handleSelectionRiver(arr1)
    const arr2 = areaList.value.filter((e) => {
      if (quyuId.includes(e.id)) {
        return e
      }
    })
    arr2.forEach((row) => {
      multipleTableAreaRef.value.toggleRowSelection(row, true)
    })
    handleSelectionCalc(arr2)
  }
}
async function handleOpenModal(value) {
  dialogVisible.value = true
  state.title = value.id ? '修改流域' : '新建流域'
  // 获取河系
  await rsysList()
  // 获取全部区域
  await getAllArea()
  if (value.id) {
    handleBasinDetail(value.id)
  }

  state.selected = false
}

defineExpose({ handleOpenModal })
//保存
function handleSave() {
  riverFormRef.value.validate(async (valid) => {
    if (valid) {
      const res = await saveBasin({
        basinId: basinObj.value.id || undefined,
        basinName: basinObj.value.basinName,
        basinDesc: basinObj.value.basinDesc,
        zoneId: props.watershedId,
        children: [...rsysData.value, ...areaData.value]
      })
      if (res.code === 200) {
        ElMessage.success('保存成功')
        closeBasin()
        handleClose()
      }
    }
  })
}
function handleClose() {
  basinObj.value = {}
  multipleTableRef.value.clearSelection()
  multipleTableAreaRef.value.clearSelection()
  dialogVisible.value = false
  riverFormRef.value.resetFields()
}
</script>

<style lang="less" scoped>
.areaTable {
  height: 300px;
}
.river-modal {
  // width: 100%;
  // height: 100%;
  .my-header {
    height: 35px;
    border-bottom: 2px solid #eee;
  }
  .river-box {
    display: flex;
    width: 100%;
    height: 100%;
    .el-form {
      width: 100%;
    }
    .box-right {
      display: flex;
      justify-content: space-around;
      .el-form-item {
        width: 50%;
      }
    }
  }
}
</style>
